package com.whmnx.home.ui.fragment;


import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.android.material.tabs.TabLayout;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.utils.UItils;
import com.whmnx.home.BR;
import com.whmnx.home.R;
import com.whmnx.home.databinding.FragmentHome2Binding;
import com.whmnx.home.ui.adapter.BaseFragmentPagerAdapter;

import java.util.List;

import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;

/**
 *
 * @author goldze
 * @date 2017/7/17
 * 抽取的二级BasePagerFragment
 */

public abstract class BasePagerFragment extends BaseFragment<FragmentHome2Binding, BaseViewModel> implements AMapLocationListener {

    private List<Fragment> mFragments;
    private List<String> titlePager;
    private boolean flag = false;
    private String city;

    protected abstract List<Fragment> pagerFragment();

    protected abstract List<String> pagerTitleString();

    private Disposable subscribe;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    public double latitude;
    public double longitude; //经度

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_home2;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            //...隐藏的操作
            RxBus.getDefault().post(EventConstants.QIEHUAN);
        } else {

            //...隐藏的操作
            // isHidden = false;
            //  TXLog.d(TAG,   isHidden + "");
            //  ToastUtil.toastShortMessage(isHidden + "");
            //  ToastUtil.toastShortMessage(isHidden + "----onHiddenChanged");
        }
    }



    @Override
    public void initData() {
        //定位
        getLocationInfo();
        mFragments = pagerFragment();
        titlePager = pagerTitleString();
      //  getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
     //   getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
      //  UItils.setStatusBar(true,getActivity());
        //设置Adapter
        BaseFragmentPagerAdapter pagerAdapter = new BaseFragmentPagerAdapter(getChildFragmentManager(), mFragments, titlePager);
        binding.viewPager.setAdapter(pagerAdapter);
        binding.tabs.setupWithViewPager(binding.viewPager);
        binding.viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(binding.tabs));
        binding.viewPager.setOffscreenPageLimit(2);
        binding.viewPager.setCurrentItem(1);
        binding.fl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxBus.getDefault().post(EventConstants.LEFT);
            }
        });



        binding.viewPager.setOnPageChangeListener (new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int select) {
                Log. d( "dml", "onPageSelected:::::select ============ " + select) ;
                if (select == 0){
                    RxBus.getDefault().post(EventConstants.HOME);
                }else {
                    RxBus.getDefault().post(EventConstants.HOME2);
                }
            }

            @Override
            public void onPageScrolled(int positon, float arg1, int arg2 ) {
                Log. d( "dml", "onPageScrolled:::::select ============ " + positon) ;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log. d( "dml", "onPageScrollStateChanged:::::select ============ " + state) ;
            }
        });

        binding.iv2.setOnClickListener(v -> showDialog());
    }

    private void showDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_message_contact, null);
        int popWindowWidth = (int) (UItils.getDeviceDensity(getActivity()).widthPixels / 4);
        PopupWindow mPopWindow = new PopupWindow(view,popWindowWidth, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(view);
        // 设置PopupWindow的背景


        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setOutsideTouchable(true);

        //  mPopWindow.getContentView().enableBackgroundDark(false);
        // 这个很重要
      //  mPopWindow.getContentView().setFocusable(true);
     //   mPopWindow.getContentView().setFocusableInTouchMode(true);

        TextView tv = view.findViewById(R.id.tv);
        tv.setText(city);

        mPopWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mPopWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        mPopWindow.showAsDropDown(binding.iv2, 0, 0);
    }


    @Override
    public void initViewObservable() {
        subscribe = RxBus.getDefault().toObservable(Object.class)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object object){
                       if (object.equals(EventConstants.ALL)){
                            binding.rl.setBackgroundColor(getResources().getColor(R.color.tran));
                        }else if (object.equals(EventConstants.ALL2)){
                           binding.rl.setBackgroundColor(getResources().getColor(R.color.app_red));
                        }else if (object.equals(EventConstants.ALL3)){
                           binding.rl.setBackgroundColor(getResources().getColor(R.color.tran));
                       }
                    }
                });
        RxSubscriptions.add(subscribe);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(subscribe);
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
    }


    private void getLocationInfo() {
        mlocationClient = new AMapLocationClient(getActivity());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        //启动定位
        mlocationClient.startLocation();


    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
                city = aMapLocation.getCity();
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }
}
